import type { App } from 'vue';
import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import { load } from "@fingerprintjs/fingerprintjs";
import { ss } from "@/utils/storage"

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: ()=> import('@/views/noauth/login/login.vue'),
    meta: {
      show_menu: false
    }
  },
  {
    path: '/register',
    name: 'register',
    component: ()=> import('@/views/noauth/register/register.vue'),
    meta: {
      show_menu: false
    }
  },
  {
    path: '/forget',
    name: 'forget',
    component: ()=> import('@/views/noauth/forget/forget.vue'),
    meta: {
      show_menu: false
    }
  },
  //  官网介绍页
  {
    path: '/',
    name: 'index',
    component:()=>import('@/views/index/index.vue'),
    meta: {
      show_menu: false
    }
  },
  {
    path: '/dashboard/home',
    name: 'home',
    component: ()=> import('@/views/dashboard/home/home.vue'),
    meta: {
      show_menu: true
    }
  },
  {
    path: '/dashboard/profile',
    name: 'profile',
    component: ()=> import('@/views/dashboard/profile/profile.vue'),
    meta: {
      show_menu: true
    }
  },
  {
    path: '/dashboard/payment',
    name: 'payment',
    component: ()=> import('@/views/dashboard/payment/PayAttach.vue'),
    meta: {
      show_menu: true
    }
  },
  {
    path: '/dashboard/call',
    name: 'call',
    component: ()=> import('@/views/dashboard/call/call.vue'),
    meta: {
      show_menu: true
    }
  },
  {
    path: '/dashboard/billing',
    name: 'billing',
    component: ()=> import('@/views/dashboard/billing/billing.vue'),
    meta: {
      show_menu: true
    }

  }
]

export const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

export async function setupRouter(app: App) {
  app.use(router)
  await router.isReady()
  getBrowerFingerprintId()
}

const fingerJs = load()
function getBrowerFingerprintId() {
  fingerJs.then(fp => {
    fp.get().then(result => {
      const visitorId = result.visitorId;
      if (visitorId !== null || visitorId !== '') {
        localStorage.setItem("visitorId", visitorId);
      }
    });
  })
}

// 导航守卫
router.beforeEach((to,from,next)=>{
  const user:User.saveUserInfo = ss.get('user');
  if (to.path === '/login' || to.path === '/register' || to.path === '/forget'){
    next()
  }else{
    if (user === undefined || user === null || user.token === null || user.token === ''){
      next('login')
    }else{
      next();
    }
  }
})
